package com.dyw.ycgovfinance.mvp.news.newschart;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dyw.ycgovfinance.R;
import com.dyw.ycgovfinance.adapter.chart.FinanceAdapter;
import com.dyw.ycgovfinance.bean.FinanceBean;
import com.dyw.ycgovfinance.commom.Config;
import com.dyw.ycgovfinance.http.HttpService;
import com.dyw.ycgovfinance.util.LogUtil;
import com.dyw.ycgovfinance.util.schedulers.SchedulerProvider;
import com.dyw.ycgovfinance.widget.ListViewForScrollView;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Created by zak on 2017/6/20.
 */
/*Fragment创建：setUserVisibleHint()->onAttach()->onCreate()->onCreateView()->onViewCreated->onActivityCreated()->onStart()->onResume()；*/
public class FragmentNewsChart extends Fragment implements NewsChartContract.View {

    private static final String ARG_PARAM = "param";
    private String mParam;
    private TextView tvTitle;
    private TextView tvChooseDate;
    //private TextView tvTitleZi;
    private ListViewForScrollView lvFinanceReceipt;
    private ProgressDialog progDialog;
    private LinearLayout lyTopTitle;
    private LinearLayout lyContent;
    private LinearLayout lyEmpty;

    private CombinedChart mChart;
    private final int itemcount = 12;
    private NewsChartContract.Presenter mPresenter;

    private FinanceAdapter financeAdapter;
    private List<FinanceBean> financeBeanList = new ArrayList<>();
    private int chooseYear;//选择的年份
    private int chooseMonth;//选择的月份
    private int mYear, mMonth, mDay;

    protected String[] mMonths = new String[]{
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
    };
    //默认的是isFirstVisibles true ,刚进来的时候分两种情况
    //1.如果切过来的时候 setVisibleHint在OnCreate之前调用，那isFirstVisible为true，这个时候不进行任何操作；
    //等方法执行到onActivityCreated的时候，在执行一次setUserVisibleHint 这个时候把默认的是isFirstVisibles 设为false
    //然后这个时候调用setUserVISIBLEhINT为true  去获取数据
    //2.如果是后面再次切过来，那isFirstVisible已经为false，那就可以直接通过setUserVisibleHint获取数据了

    //代表这个界面是不是第一次被使用
    boolean isFirstUsed = true;
    boolean isGetData = false;
    //private String[] mDistrict;
    private List<String> mDistrict = new ArrayList<>();

    public static FragmentNewsChart newInstance(String param) {

        Bundle args = new Bundle();
        FragmentNewsChart fragment = new FragmentNewsChart();
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new NewsChartPresenter(this, SchedulerProvider.getInstance(), HttpService.Factory.create(Config.URL_BASE_IN_USE));
        Calendar c = Calendar.getInstance();
        int currentYear = c.get(Calendar.YEAR);
        int currentMonth = c.get(Calendar.MONTH);

        /*if (currentMonth == 0) {
            chooseYear = currentYear - 1;
            chooseMonth = 12;
        } else {
            chooseYear = currentYear;
            chooseMonth = currentMonth;
        }*/
    }

    //创建view
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_finance_chart, container, false);
        assignView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //选择日期年月
        tvChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //onCreateDialog(0);
                Calendar c = Calendar.getInstance(Locale.CHINA);
                Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
                mYear = dateAndTime.get(Calendar.YEAR);
                mMonth = dateAndTime.get(Calendar.MONTH);
                mDay = dateAndTime.get(Calendar.DAY_OF_MONTH);
                MonPickerDialog monPickerDialog = new MonPickerDialog(getActivity(), mDateSetListner, mYear, mMonth,
                        mDay);
                monPickerDialog.show();

            }
        });
        //initData();
        //tvTitle.setText(chooseYear + "年" + chooseMonth + "月份全市公共财政预算收入完成情况表");
        //查询上个月的数据
        /*if (chooseMonth < 10) {
            String searchdate = chooseYear + "-0" + chooseMonth;
            mPresenter.getSearchReport(searchdate);
        } else {
            String searchdate = chooseYear + "-" + chooseMonth;
            mPresenter.getSearchReport(searchdate);
        }*/
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //fragment 可见的情况下 进行加载数据。不可见则不加载
        if (getUserVisibleHint() == true) {
            if (isFirstUsed == true) {
                isFirstUsed = false;
                setUserVisibleHint(true);
            }
            //不可见，说明fragment已经初始话完成,就直接把isFirstVisible改为false 再次切过来的时候就直接可以加载数据了
        } else {
            isFirstUsed = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // LogUtil.e("CartVisible");
        if (getUserVisibleHint()) {
            LogUtil.e("MyShuoShuoVisible");
            //如果不是firstvisible才去进行下面的操作  因为第一次很可能出现各种问题
            if (isFirstUsed == false) {
                if (isGetData == false) {
                  /*  if (chooseMonth < 10) {
                        String searchdate = chooseYear + "-0" + chooseMonth;
                        mPresenter.getSearchReport(searchdate);
                    } else {
                        String searchdate = chooseYear + "-" + chooseMonth;
                        mPresenter.getSearchReport(searchdate);
                    }*/
                    mPresenter.searchNewestData();
                }

            }
        } else {
            LogUtil.e("faXianFragmentVisible");
        }
    }

    public void initData() {

        mChart.getDescription().setEnabled(false);
        mChart.setBackgroundColor(Color.WHITE);
        mChart.setDrawGridBackground(false);
        mChart.setDrawBarShadow(false);
        mChart.setHighlightFullBarEnabled(false);
        mChart.setDragEnabled(true);// 是否可以拖拽
        mChart.setScaleEnabled(true);// 是否可以缩放
        mChart.setContentDescription("放大查看详情");
        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        //图例设置,设置标示，就是那个一组y的value的
        Legend l = mChart.getLegend();
        l.setWordWrapEnabled(true);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        //右边的y轴
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setDrawGridLines(false);//设置显示Y轴表格线
        rightAxis.setAxisMinimum(-20f); // this replaces setStartAtZero(true)
        //左边的y轴
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);//设置显示Y轴表格线
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //x轴样式设置
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的文字在底部
        xAxis.setLabelRotationAngle(-60);//设置x轴字体显示角度
        xAxis.setLabelCount(mDistrict.size());
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                //return mMonths[(int) value % mMonths.length];
                return mDistrict.get((int) value % mDistrict.size());
            }
        });

        CombinedData data = new CombinedData();
        data.setData(generateLineData());//设置折线图
        data.setData(generateBarData());//设置条形图
        xAxis.setAxisMaximum(data.getXMax() + 0.25f);
        mChart.setData(data);
        // data.setValueTypeface(mTfLight);
        mChart.invalidate();
    }

    private LineData generateLineData() {

        LineData d = new LineData();

        ArrayList<Entry> entries = new ArrayList<Entry>();
        ArrayList<Entry> entries2 = new ArrayList<Entry>();

        for (int index = 0; index < mDistrict.size(); index++) {
            float yearBudgetPercent = Float.parseFloat(financeBeanList.get(index).getYearBudgetPercent());
            entries.add(new Entry(index + 0.5f, yearBudgetPercent));
        }
        //entries.add(new Entry(index + 0.5f, getRandom(15, 5)));

        LineDataSet set = new LineDataSet(entries, "占年底预算%");
        set.setColor(Color.rgb(240, 238, 70));
        set.setLineWidth(2.5f);
        set.setCircleColor(Color.rgb(240, 238, 70));//设置圆圈的颜色
        set.setCircleRadius(5f);
        set.setFillColor(Color.rgb(240, 238, 70));
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setDrawValues(false);//不绘制线的数据
        set.setValueTextSize(10f);
        set.setValueTextColor(Color.rgb(240, 238, 70));
        set.setAxisDependency(YAxis.AxisDependency.RIGHT);//设置线数据依赖于左侧y轴

        for (int index = 0; index < mDistrict.size(); index++) {
            float amplificationPercent = Float.parseFloat(financeBeanList.get(index).getAmplificationPercent());
            entries2.add(new Entry(index + 0.5f, amplificationPercent));
        }
        //entries2.add(new Entry(index + 0.5f, getRandom(15, 10)));

        LineDataSet set2 = new LineDataSet(entries2, "比上年增减%");
        set2.setColor(Color.rgb(23, 197, 255));
        set2.setLineWidth(2.5f);
        set2.setCircleColor(Color.rgb(23, 197, 255));
        set2.setCircleRadius(5f);
        set2.setFillColor(Color.rgb(23, 197, 255));
        set2.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set2.setDrawValues(false);
        set2.setValueTextSize(10f);
        set2.setValueTextColor(Color.rgb(23, 197, 255));
        set2.setAxisDependency(YAxis.AxisDependency.RIGHT);

        d.addDataSet(set);
        d.addDataSet(set2);
        return d;
    }

    private BarData generateBarData() {
        //柱状图有两个
        ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
        ArrayList<BarEntry> entries2 = new ArrayList<BarEntry>();

        for (int index = 0; index < mDistrict.size(); index++) {
            float yearBudget = Float.parseFloat(financeBeanList.get(index).getYearBudget());
            float cumulateAmount = Float.parseFloat(financeBeanList.get(index).getCumulateAmount());
            entries1.add(new BarEntry(0, yearBudget));
            entries2.add(new BarEntry(0, cumulateAmount));
            /*entries1.add(new BarEntry(0, getRandom(25, 25)));
            entries2.add(new BarEntry(0, getRandom(13, 12)));*/
        }

        BarDataSet set1 = new BarDataSet(entries1, "年度预算数");
        set1.setColor(Color.rgb(60, 220, 78));
        set1.setValueTextColor(Color.rgb(60, 220, 78));
        set1.setValueTextSize(10f);
        set1.setDrawValues(false);
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);

       /* BarDataSet set2 = new BarDataSet(entries2, "");
        set2.setStackLabels(new String[]{"Stack 1", "Stack 2"});
        set2.setColors(new int[]{Color.rgb(61, 165, 255), Color.rgb(23, 197, 255)});
        set2.setValueTextColor(Color.rgb(61, 165, 255));
        set2.setValueTextSize(10f);
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);*/
        BarDataSet set2 = new BarDataSet(entries2, "金额");
        set2.setColors(Color.rgb(61, 165, 255));
        set2.setValueTextColor(Color.rgb(61, 165, 255));
        set2.setValueTextSize(10f);
        set2.setDrawValues(false);
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
        // (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"

        BarData d = new BarData(set1, set2);
        d.setBarWidth(barWidth);

        // make this BarData object grouped
        d.groupBars(0, groupSpace, barSpace); // start at x = 0

        return d;
    }


    protected float getRandom(float range, float startsfrom) {
        return (float) (Math.random() * range) + startsfrom;
    }

    @Override
    public void setPresenter(NewsChartContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void showLoading() {
        progDialog = new ProgressDialog(getActivity());
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在加载...");
        progDialog.show();
    }

    @Override
    public void dismissLoading() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    //获取数据成功
    @Override
    public void onGetSuccess(List<FinanceBean> financeBeans) {
        isGetData = true;
        if (financeBeans.size() == 0) {
            //Toast.makeText(getActivity(), "当月没有数据", Toast.LENGTH_SHORT).show();
            lyContent.setVisibility(View.GONE);
            lyEmpty.setVisibility(View.VISIBLE);
            return;
        } else {
            lyContent.setVisibility(View.VISIBLE);
            lyEmpty.setVisibility(View.GONE);
        }
        financeBeanList.clear();
        financeBeanList.addAll(financeBeans);

        financeAdapter = new FinanceAdapter(getActivity(), financeBeanList);
        lvFinanceReceipt.setAdapter(financeAdapter);
        //绘制图表
        //先获取x轴数据
        mDistrict.clear();
        for (int i = 0; i < financeBeanList.size(); i++) {
            mDistrict.add(financeBeanList.get(i).getArea());
        }

        initData();
    }

    @Override
    public void onGetError(String tip) {
        Toast.makeText(getActivity(), tip, Toast.LENGTH_SHORT).show();
    }

    //获取最新的数据
    @Override
    public void getNewestDataSuccess(List<FinanceBean> financeBeans) {
        isGetData = true;
        if (financeBeans.size() == 0) {
            //Toast.makeText(getActivity(), "当月没有数据", Toast.LENGTH_SHORT).show();
            lyContent.setVisibility(View.GONE);
            lyEmpty.setVisibility(View.VISIBLE);
            return;
        } else {
            String time = financeBeans.get(0).getReportMonth();
            tvTitle.setText(time.split("-")[0] + "年" + time.split("-")[1] + "月份全市公共财政预算收入完成情况表");
            lyContent.setVisibility(View.VISIBLE);
            lyEmpty.setVisibility(View.GONE);
        }
        financeBeanList.clear();
        financeBeanList.addAll(financeBeans);

        financeAdapter = new FinanceAdapter(getActivity(), financeBeanList);
        lvFinanceReceipt.setAdapter(financeAdapter);
        //绘制图表
        //先获取x轴数据
        mDistrict.clear();
        for (int i = 0; i < financeBeanList.size(); i++) {
            mDistrict.add(financeBeanList.get(i).getArea());
        }

        initData();
    }

    public void assignView(View view) {
        tvTitle = (TextView) view.findViewById(R.id.tv_title);
        tvChooseDate = (TextView) view.findViewById(R.id.tv_choose_date);
        //tvTitleZi = (TextView) view.findViewById(R.id.tv_title_zi);
        lvFinanceReceipt = (ListViewForScrollView) view.findViewById(R.id.lv_finance_receipt);
        mChart = (CombinedChart) view.findViewById(R.id.chart_finance_receipt);
        lyTopTitle = (LinearLayout) view.findViewById(R.id.ly_topTitle);
        lyContent = (LinearLayout) view.findViewById(R.id.ly_content);
        lyEmpty = (LinearLayout) view.findViewById(R.id.ly_empty);

        lyTopTitle.setFocusable(true);
        lyTopTitle.setFocusableInTouchMode(true);
        lyTopTitle.requestFocus();

        lvFinanceReceipt.setFocusable(false);
    }

    private DatePickerDialog.OnDateSetListener mDateSetListner = new DatePickerDialog.OnDateSetListener() {


        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            String mm;
            String dd;
            if (monthOfYear <= 9) {
                mMonth = monthOfYear + 1;
                mm = "0" + mMonth;
            } else {
                mMonth = monthOfYear + 1;
                mm = String.valueOf(mMonth);
            }
            if (dayOfMonth <= 9) {
                mDay = dayOfMonth;
                dd = "0" + mDay;
            } else {
                mDay = dayOfMonth;
                dd = String.valueOf(mDay);
            }
            mDay = dayOfMonth;
            tvTitle.setText(mYear + "年" + mMonth + "月份全市公共财政预算收入完成情况表");
            //tvTitleZi.setText(mYear + "年" + mMonth + "月全市公共财政预算收入完成情况表");
            String searchdate = mYear + "-" + mm;
            Log.e("产迅数据", searchdate);
            mPresenter.getSearchReport(searchdate);
        }
    };
}
